//
//  PictureSelectorController.swift
//  sinazd
//
//  Created by apple on 16/3/16.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

private let PictureCellID = "PictureCellID"

private let pictureCellMargin:CGFloat = 5
private let coloumCount:CGFloat = 4
private let MAXCOUNT = 5

class PictureSelectorController: UICollectionViewController {

    //保存选中准备发布的照片
    var imageList = [UIImage]()
    
    init() {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        
        let w = (ScreenWidth - (coloumCount + 1) * pictureCellMargin) / coloumCount
        
        layout.itemSize = CGSize(width: w, height: w)
        
        
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: PictureCellID)

    }

 
}

//遵守协议
//必选的协议方法 在swift中必须实现 不实现默认报错
extension PictureSelectorController: PictureSelectorCellDelegate{
    func userWillChoosePicture() {
        //选择图片  UIImagePickerController
        let picker = UIImagePickerController()
        //指定选择器的代理
        picker.delegate = self
        //设置图片允许编辑  在上传用户头像的时候需要开启这个属性
        //        picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    func userWillDeletePicture(cell:PictureSelectorCell) {
        
        if let indexPath = collectionView?.indexPathForCell(cell) {
            //3.获取对应的item 删除数组中对应角标下的元素
            imageList.removeAtIndex(indexPath.item)
            
            //刷新页面
            collectionView?.reloadData()

    }
    }
}



extension PictureSelectorController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //实现协议方法  一旦实现了这个协议方法之后  图片选择器的消失的权利 就交给了程序员管理
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //        print(image)
        //        print(editingInfo)
        //将选择的图片保存起来
        imageList.append(image)
        //刷新界面
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}


//数据源方法
extension PictureSelectorController {

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       
        let delta = imageList.count == MAXCOUNT ? 0 : 1
        
        return imageList.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellID, forIndexPath: indexPath) as! PictureSelectorCell
        
       cell.selectorDelegate = self
        
       cell.backgroundColor = UIColor.randomColor()
        
        if indexPath.item == imageList.count {
            //加载最后一个cell的时候  会执行这个分支
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }
        
        
        return cell
    }
    
}


//声明协议
protocol PictureSelectorCellDelegate: NSObjectProtocol {
    
    //声明协议方法
    func userWillChoosePicture()
    
    //用户将要删除图片
    func userWillDeletePicture(cell:PictureSelectorCell)

    
}

class PictureSelectorCell:UICollectionViewCell {
    
    weak var selectorDelegate: PictureSelectorCellDelegate?
    
    
    var image: UIImage? {
        didSet {
            deleteBtn.hidden = image == nil

            addBtn.setImage(image, forState: .Normal)
        }
    }

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
 
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置UI界面
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(contentView.snp_top)
        }
        
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        
        
        addBtn.imageView?.contentMode = .ScaleAspectFill

    }
    
    
 
    private lazy var addBtn: UIButton = UIFactory.buttonWithImage(nil, backImageName: "compose_pic_add")
    private lazy var deleteBtn: UIButton = UIFactory.buttonWithImage(nil, backImageName: "compose_photo_close")

    
        //添加图片的按钮点击事件
    @objc private func addBtnDidClick() {
        
        if image == nil {
        //使用代理对象 调用协议方法
        selectorDelegate?.userWillChoosePicture()
        }
    }
    
    //删除图片的按钮点击事件
    @objc private func deleteBtnDidClick() {
        selectorDelegate?.userWillDeletePicture(self)
    }

    
}

